import React from 'react';
import { Link, useParams } from 'react-router-dom';
import { useNavigate } from 'react-router-dom'
import { Table, Space, Card, Breadcrumb, Form, Button, Radio, DatePicker, Select,Modal, Input,message,Upload ,Pagination} from 'antd'
import { PlusOutlined } from '@ant-design/icons';
import { useForm } from 'antd/lib/form/Form';
import { useEffect, useState } from 'react'
import axios from 'axios';
const { TextArea } = Input;

const DohomeworkList = () => {
    let {courseid,homeworkid } = useParams();
    const navigate = useNavigate(); // 使用 useNavigate 替代 useHistory
    const [form] = useForm();
  const [data, setData] = useState([]);
  const [isaddModalVisible, setIsaddModalVisible] = useState(1);
  const [addData, setaddData] = useState(null);
  const [fileList, setFileList] = useState([]);


  
  useEffect(() => {
    const studentid = localStorage.getItem('studentid');
    axios.get('http://localhost:8000/getstuhomework', {
      params: { courseid, homeworkid, studentid }
    })
      .then(response => {
        console.log("接受到的数据" + JSON.stringify(response.data.list));
        setData(response.data.list);
  
        console.log("存储到的数据" + JSON.stringify(data));
      })
      .catch(error => {
        console.error('Error fetching data:', error);
      });
  }, []);
  
  

  const handleChange = info => {
    let fileList = [...info.fileList];
    fileList = fileList.slice(-3); // 最多显示3个文件
  
    // 更新 fileList 状态
    setFileList(fileList);
    console.log(fileList);
  
    if (info.file.status === 'done') {
      message.success(`${info.file.name} 文件上传成功`);
    } else if (info.file.status === 'error') {
      message.error(`${info.file.name} 文件上传失败`);
    }
  };
  
  const handleCustomRequest = async (options) => {
    const { file, onSuccess, onError } = options;

    const formData = new FormData();
    formData.append('file', file);

    try {
        const response = await fetch("http://localhost:8000/homeworkupload", {
            method: "POST",
            body: formData,
        });
        if (response.ok) {
            const data = await response.json();
            const newFilename = data.newFilename;
            console.log(newFilename);
            onSuccess(newFilename); // 将 newFilename 传递给 onSuccess
        } else {
            onError(); // 文件上传失败
        }
    } catch (error) {
        console.error("Error uploading file:", error);
        onError(); // 文件上传失败
    }
};
  const handleRemove = file => {
    const imageData = file.response;
  
    console.log('要删除的图片信息:', imageData);
  
    // 使用 axios 发送 DELETE 请求
    axios.post('http://localhost:8000/teacherupload', { imageData })
    .then(response => {
        console.log('成功删除服务器上的图片');
        message.success(`文件删除成功`);
        // 可以在这里执行其他操作
    })
    .catch(error => {
        console.error('删除图片时出错:', error);
    });
    console.log(fileList);
  
  };
  const handleAddHomework = () => {
    const formValues = form.getFieldsValue(); // 获取表单字段值
    const studentid = localStorage.getItem('studentid');
    const name = localStorage.getItem('usersname');

    const values = {
        ...formValues,
        courseid:courseid,
        studentid: studentid,
        studentname: name,
        homeworkid: homeworkid,
    };

    console.log('表单内容:', values);
    values.img = []; // 初始化存放每一项的response的数组
    
    fileList.forEach(item => {
        values.img.push(item.response); // 把filelist里每一项的response都存进values.img里
    });
     values.img = values.img.join(', ');

     Modal.confirm({
        title: '确认提交作业',
        content: '一旦提交则无法修改,是否确定提交',
        onOk() {
            axios.post('http://localhost:8000/studenthomework', { values })
                .then(response => {
                    console.log('成功发送到后端并收到响应:', response.data);
                    navigate(`/Layoutstudent/course/${courseid}`);
                })
                .catch(error => {
                    console.error('与后端通信时发生错误:', error);
                });
        },
        onCancel() {
            console.log('用户取消提交作业');
        },
    });
};


    return (
        <div>
        <div>
          <Breadcrumb>
            <Breadcrumb.Item><Link to="/Layoutstudent/coursepage">Courses</Link></Breadcrumb.Item>
            <Breadcrumb.Item><Link to={`/Layoutstudent/course/${courseid}`}>课程详情</Link></Breadcrumb.Item>
            <Breadcrumb.Item>作业管理</Breadcrumb.Item>
          </Breadcrumb>
        </div>
        <div>
          <Form
            form={form}
            labelCol={{ span: 6 }}
            wrapperCol={{ span: 16 }}
            style={{ marginTop: '50px' }}
          >
            {data.length === 0 ? (
              <>
                <Form.Item label="作业内容" name="text">
                  <TextArea rows={11} />
                </Form.Item>
                <Form.Item label="图片列表">
                  <Upload
                    listType="picture-card"
                    fileList={fileList}
                    onChange={handleChange}
                    customRequest={handleCustomRequest}
                    onRemove={handleRemove}
                  >
                    <div>
                      <PlusOutlined />
                      <div style={{ marginTop: 8 }}>上传图片</div>
                    </div>
                  </Upload>
                </Form.Item>
                <Form.Item wrapperCol={{ offset: 6 }}>
                  <Button type="primary" onClick={handleAddHomework}>
                    提交作业
                  </Button>
                </Form.Item>
              </>
            ) : (
              <p>作业已提交</p>
            )}
          </Form>
        </div>
      </div>
    );
}

export default DohomeworkList;
